package com.tx.order.controller;

import com.tx.order.client.ProductClient;
import com.tx.order.dataobject.ProductInfo;
import com.tx.order.dto.CartDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
public class ClientController {
    Logger logger = LoggerFactory.getLogger(ClientController.class);

//    RestTemplate第二种方法
//    @Autowired
//    private LoadBalancerClient loadBalancerClient;

//    RestTemplate第三种方法
//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    @GetMapping("/getProductMsg")
    public String getProductMsg(){

        // RestTemplate第一种方式:直接使用restTemplate，url写死
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject("http://127.0.0.1:8080/msg", String.class);

        // RestTemplate第二种方式:利用loadBalancerClient通过应用名获取url，然后再使用restTemplate
//        RestTemplate restTemplate = new RestTemplate();
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String url = String.format("http://s%:%s",
//                serviceInstance.getHost(),
//                serviceInstance.getPort())+"/msg";
//        String response = restTemplate.getForObject(url, String.class);

        // RestTemplate第三种方式:利用@LoadBalanced，可在restTemplate里使用应用名字
//        String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);

        String response = productClient.productMsg();

        logger.info("response="+response);
        return response;
    }


    @GetMapping("/getProductList")
    public String getProductList(){
        List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("1578751","1578753"));
        logger.info("response="+productInfoList);
        return "ok";
    }

    @GetMapping("/productDecreaseStock")
    public String productDecreaseStock(){
        productClient.decreaseStock(Arrays.asList(new CartDTO("1578753",2)));
        return "ok";
    }

}
